<?php

namespace App\Services;

use Illuminate\Http\UploadedFile;
use Image;
use Storage;
use Str;
use App\Modules\Libs\Vars;
use zgldh\QiniuStorage\QiniuStorage;
use Dingo\Api\Routing\Helpers;

class QiniuImageUploadService extends ImageUploadService
{
    use Helpers;
    public $url = null;
    public $path = null;
    //public $prefixPath = ''; // 子目录前缀
    public $prefixPath = 'shopApi/'; // 子目录前缀

    public function save(UploadedFile $file, $file_prefix = '', $max_width = 800)
    {
        $this->path = null;
        $this->url = null;
        // 获取文件的扩展名，symfony框架自带的，根据mime/type猜测扩展名，猜不到就jpg
        $extension = strtolower($file->guessExtension()) ?: 'jpg';

        // 如果上传的不是图片将终止操作
        if (!in_array($extension, $this->allowed_ext)) {
            //throw new \Exception('图片格式无效');
            return $this->response->errorBadRequest('图片格式无效');
        }

        // 图片上传的目标物理地址,为了resize，需要先把图片从临时目录移过来，上传之后再删除
        $tmpFullPath = Vars::$vars['FileUploadRoot'] . '/' . Vars::$vars['ImagePath'] . '/tmp';

        // 拼接文件名，加前缀是为了增加辨析度，前缀可以是相关数据模型的 ID;值如：images/2023-05-11/avatar_1683797334_cvKSOaVeoq.jpg
        $filename = $file_prefix . '_' . time() . '_' . Str::random(10) . '.' . $extension;

        // 从临时目录移到目标位置
        $file->move($tmpFullPath, $filename);

        // 图形resize处理
        $fullFilePath = $tmpFullPath . '/' . $filename;
        $width = getimagesize($fullFilePath)[0];

        // 如果超过最大图片宽度，就进行裁剪
        if ($max_width < $width && $extension !== 'gif') {
            // 此类中封装的函数，用于裁剪图片
            $this->reduceSize($fullFilePath, $max_width);
        }

        // 构建存储的文件夹规则，值如：uploads/images/2023-05-11
        $folderName = Vars::$vars['ImageUploadPath'];
        $qiniuFilePath = "{$this->prefixPath}$folderName/$filename";
        // 将图片保存到目标存储路径中
        $disk = QiniuStorage::disk('qiniu');
        try {
            //dd($qiniuFilePath,$fullFilePath);
            $disk->put($qiniuFilePath, file_get_contents($fullFilePath));
        } catch (\Exception $e) {
            throw $e;
        }
        // 删除临时文件

        Storage::disk('admin')->delete(Vars::$vars['ImagePath'] . '/tmp/' . $filename);

        $this->url = $disk->downloadUrl($qiniuFilePath,'https');
        // 从完整url中截取后面的部分，方便切换域名
        return $this->path = substr($this->url, strpos($this->url, 'images/')); // 返回相对路径

    }

    public function delete(?string $imagePath)
    {
        $disk = \Illuminate\Support\Facades\Storage::disk('qiniu');

        if ($imagePath) {
            $imagePath = $this->prefixPath . $imagePath;
        }
        if (!$imagePath || !$disk->exists($imagePath)) {
            return $this->response->errorBadRequest('资源不存在或已经被删除');
        }

        // 删除单条文件
        $disk->delete($imagePath);
        return true;
    }

    public function saveBase64(string $base64Img, $file_prefix = '', $max_width = 800)
    {
        preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64Img, $res);
        $image = base64_decode(str_replace($res[1], '', $base64Img));
        $extension = $res[2];

        // 图片上传的目标物理地址,为了resize，需要先把图片从临时目录移过来，上传之后再删除
        $tmpFullPath = Vars::$vars['FileUploadRoot'] . '/' . Vars::$vars['ImagePath'] . '/tmp';

        // 拼接文件名，加前缀是为了增加辨析度，前缀可以是相关数据模型的 ID;值如：avatar_1683797334_cvKSOaVeoq.jpg
        $filename = $file_prefix . '_' . time() . '_' . Str::random(10) . '.' . $extension;

        // 图形resize处理
        $fullFilePath = $tmpFullPath . '/' . $filename;

        // 保存到临时目录,此时会在服务器临时目录保存成jpg，然后就可以resize了
        Storage::disk('admin')->put(Vars::$vars['ImagePath'] . '/tmp/' . $filename, $image);

        $width = getimagesize($fullFilePath)[0];

        // 如果超过最大图片宽度，就进行裁剪
        if ($max_width < $width && $extension !== 'gif') {
            // 此类中封装的函数，用于裁剪图片
            $this->reduceSize($fullFilePath, $max_width);
        }

        // 构建存储的文件夹规则，值如：uploads/images/2023-05-11
        $folderName = Vars::$vars['ImageUploadPath'];
        $qiniuFilePath = "{$this->prefixPath}$folderName/$filename";
        // 将图片保存到目标存储路径中
        $disk = QiniuStorage::disk('qiniu');
        try {
            $disk->put($qiniuFilePath, file_get_contents($fullFilePath));
        } catch (\Exception $e) {
            throw $e;
        }
        // 删除临时文件
        Storage::disk('admin')->delete(Vars::$vars['ImagePath'] . '/tmp/' . $filename);

        $this->url = $disk->downloadUrl($qiniuFilePath);
        // 从完整url中截取后面的部分，方便切换域名
        return $this->path = substr($this->url, strpos($this->url, 'images/')); // 返回相对路径
    }
}
